package cn.rwklyd.ecommerce.service;

import cn.rwklyd.ecommerce.mapper.UserMapper;
import cn.rwklyd.ecommerce.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

/**
 * @author 键盘书生
 * @date 2024/12/2
 */
@Service
@Slf4j
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserLogService userLogService;  // 引入日志服务

    //根据用户名查询用户信息
    public Users getUserByName(String userName) {
        Users e = userMapper.getUserByName(userName);
        e.setPassword("保密字段");
        return e;
    }

    //根据用户ID查询用户信息
    public Users getUserById(String id) {
        Users e = userMapper.getUserById(id);
        e.setPassword("保密字段");
        return e;
    }

    //用户添加商品到购物车
    public void addCart(String userId,String productId,Integer quantity,Double totalPrice) {
        userMapper.addProductToCart(userId, productId, quantity, totalPrice);
    }

    //获取当前用户加入购物车中的商品
    public List<Cart> getCartList(String userId) {
        List<Cart> cartList = userMapper.getCartList(userId);
        for (Cart cart : cartList) {
            cart.setProduct(userMapper.getProductById(String.valueOf(cart.getProductId())));
        }
        return cartList;
    }

    //用户结算商品
    @Transactional(rollbackFor = Exception.class)
    public boolean settlement(SettlementRequest request) {
        Users user = userMapper.getUserById(request.getUserId());  // 获取用户信息
        boolean success = false;
        try {
            if (user.getBalance() > request.getTotalPrice()) {
                user.setBalance(user.getBalance() - request.getTotalPrice()); // 用户余额减去商品价格
                if (userMapper.updateUser(user) > 0) { // 更新用户余额
                    for (Long cartId : request.getCartIds()) {
                        Cart cart = userMapper.getCartById(request.getUserId(), cartId);  // 获取购物车信息
                        if (cart != null) {
                            int i = userMapper.updateCartPayStatus(request.getUserId(), cartId); // 更新购物车状态为已支付
                            if (i > 0) {
                                Product product = userMapper.getProductById(String.valueOf(cart.getProductId()));
                                userMapper.updateProductStock(product.getProductId(), product.getStock() - cart.getQuantity());
                                success = true;
                            } else {
                                throw new RuntimeException("支付失败：更新购物车状态失败"); // 更新失败时抛出异常
                            }
                        } else {
                            throw new RuntimeException("支付失败：购物车信息不存在"); // 购物车信息不存在时抛出异常
                        }
                    }
                } else {
                    throw new RuntimeException("支付失败：更新用户余额失败"); // 更新用户余额失败时抛出异常
                }
            } else {
                throw new RuntimeException("支付失败：余额不足"); // 余额不足时抛出异常
            }
        } catch (Exception e) {
            log.error("支付异常，用户ID: {}, 错误信息: {}", request.getUserId(), e.getMessage());
            throw e; // 抛出异常以触发事务回滚
        } finally {
            // 插入操作日志
            UserLog userLog = new UserLog();
            userLog.setUserId(Integer.valueOf(request.getUserId())); // 操作对象id
            userLog.setActionType("play"); // 操作类型
            userLog.setSuccess(success); // 操作是否成功
            userLog.setActionDescription("用户ID：" + request.getUserId() + "，结算商品:" + request.getCartIds() + "，商品总价：" + request.getTotalPrice());
            userLogService.insert(userLog); // 插入日志记录
        }
        return success; // 返回支付是否成功
    }

    //查看用户历史订单
    public List<Cart> getHistoryOrder(String userId) {
        List<Cart> cartList = userMapper.getHistoryOrder(userId);
        for (Cart cart : cartList) {
            cart.setProduct(userMapper.getProductById(String.valueOf(cart.getProductId())));
        }
        return cartList;
    }

    //删除历史订单信息
    public Integer deleteHistoryOrder(Long cartId,String userId) {
        return userMapper.deleteHistoryOrder(cartId,userId);
    }

    //修改用户信息
    public Integer updateUser(Users user) {
        Users oldUser = userMapper.getUserById(String.valueOf(user.getId()));
        if(user.getPassword().equals("保密字段")){
            user.setPassword(oldUser.getPassword());
        }
        Users e = userMapper.getUserByName(user.getUsername());
        if(e!=null){
            if(user.getId()==e.getId()){
                return userMapper.updateUser(user);
            }else {
                return 401;
            }
        }
        return userMapper.updateUser(user);
    }




}
